package com.nxmu.hire.service.impl;

import com.alibaba.fastjson.JSON;
import com.nxmu.hire.common.exception.ServiceException;
import com.nxmu.hire.dao.ApplyMapper;
import com.nxmu.hire.model.Apply;
import com.nxmu.hire.model.ApplyExample;
import com.nxmu.hire.model.GradeCoefficient;
import com.nxmu.hire.model.User;
import com.nxmu.hire.model.apply.ApplyMessage;
import com.nxmu.hire.model.apply.achieve.AchievementApply;
import com.nxmu.hire.model.apply.award.AwardApply;
import com.nxmu.hire.model.apply.guide.GuideApply;
import com.nxmu.hire.model.apply.manage.ManageApply;
import com.nxmu.hire.model.apply.study.StudyApply;
import com.nxmu.hire.model.apply.works.*;
import com.nxmu.hire.model.enums.ClassCategory;
import com.nxmu.hire.service.ApplyService;
import com.nxmu.hire.service.GradeCoefficientService;
import com.nxmu.hire.service.UserService;
import com.nxmu.hire.utils.HireUtil;
import com.nxmu.hire.vo.ApplyReqVo;
import com.nxmu.hire.vo.ApplyResVo;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class ApplyServiceImpl implements ApplyService {

    @Autowired
    private ApplyMapper applyMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private GradeCoefficientService gradeCoefficientService;

    /**
     * 根据教师编号查询所有的记录
     *
     * @param userId
     * @return
     */
    @Override
    public List<Apply> findByUserId(String userId) {
        ApplyExample applyExample = new ApplyExample();
        applyExample.createCriteria().andTeacherIdEqualTo(userId);
        return applyMapper.selectByExample(applyExample);
    }

    /**
     * 申报
     * @param applyReqVo
     * @throws ServiceException
     */
    @Transactional
    @Override
    public ApplyResVo save(ApplyReqVo applyReqVo) throws ServiceException {
       if (applyReqVo.getDraft().equals(1) || applyReqVo.getDraft().equals(0)) {
            Apply apply = new Apply();
            User user = userService.findUserByUserId(applyReqVo.getUserId());

            apply.setTeacherId(applyReqVo.getUserId());
            apply.setTeacherName(user.getUserName());
            apply.setDraft(applyReqVo.getDraft());
            apply.setApplyMessage(JSON.toJSONString(applyReqVo.getApplyMessage()));
            apply.setApplyDate(new Date());
            apply.setSchoolYear(HireUtil.countSchoolYear(LocalDate.now()));
            apply.setSemester(HireUtil.countSemester(LocalDate.now()));
            try {
                applyMapper.insert(apply);
            } catch (Exception e) {
                throw new ServiceException("申请失败");
            }
        }

        GradeCoefficient gradeCoefficient = gradeCoefficientService.findLastGradeCoefficient();

        return calculateScore(applyReqVo.getApplyMessage(),gradeCoefficient);
    }

    /**
     * 计算每一项成绩
     * @param applyMessage
     * @return
     */
    private ApplyResVo calculateScore(ApplyMessage applyMessage, GradeCoefficient gradeCoefficient) {
        ApplyResVo applyResVo = new ApplyResVo();

        // 教学工作量成绩计算
        float worksScore = worksScoreCalculate(applyMessage,gradeCoefficient);
        // 教学研究成绩计算
        float studyScore = studyScoreCalculate(applyMessage,gradeCoefficient);
        // 教学成果成绩计算
        float achieveScore = achieveScoreCalculate(applyMessage,gradeCoefficient);
        // 教学管理成绩计算
        float manageScore = manageScoreCalculate(applyMessage,gradeCoefficient);
        // 指导学生成绩计算
        float guideScore = guideScoreCalculate(applyMessage,gradeCoefficient);
        // 教学奖励成绩计算
        float awardScore = awardScoreCalculate(applyMessage,gradeCoefficient);
        // 总成绩计算
        float totalScore = 0;
        totalScore = worksScore + studyScore + achieveScore + manageScore +  guideScore + awardScore;

        applyResVo.setWorkScore(worksScore);
        applyResVo.setStudyScore(studyScore);
        applyResVo.setAchieveScore(achieveScore);
        applyResVo.setManageScore(manageScore);
        applyResVo.setGuideScore(guideScore);
        applyResVo.setAwardScore(awardScore);
        applyResVo.setTotalScore(totalScore);

        return applyResVo;
    }

    private float awardScoreCalculate(ApplyMessage applyMessage, GradeCoefficient gradeCoefficient) {
        float awardScore = 0;
        AwardApply awardApply = applyMessage.getAwardApply();

        return awardScore;
    }

    private float guideScoreCalculate(ApplyMessage applyMessage, GradeCoefficient gradeCoefficient) {
        float guideScore = 0;
        GuideApply guideApply = applyMessage.getGuideApply();
        return guideScore;
    }

    private float manageScoreCalculate(ApplyMessage applyMessage, GradeCoefficient gradeCoefficient) {
        float manageScore = 0;
        ManageApply manageApply = applyMessage.getManageApply();
        return manageScore;
    }

    private float achieveScoreCalculate(ApplyMessage applyMessage, GradeCoefficient gradeCoefficient) {
        float achieveScore = 0;
        AchievementApply achievementApply = applyMessage.getAchievementApply();
        return achieveScore;
    }

    private float studyScoreCalculate(ApplyMessage applyMessage, GradeCoefficient gradeCoefficient) {
        float studyScore = 0;
        StudyApply studyApply = applyMessage.getStudyApply();

        return studyScore;
    }

    private float worksScoreCalculate(ApplyMessage applyMessage, GradeCoefficient gradeCoefficient) {
        float worksScore = 0;

        WorksApply worksApply = applyMessage.getWorksApply();

        // 基本教学工作量
        if (worksApply.getBaseWorks() != null && !worksApply.getBaseWorks().isEmpty()){
            for (BaseWork baseWork : worksApply.getBaseWorks()) {
                if (!Objects.isNull(baseWork.getFinish()) && baseWork.getFinish().equals(1)) worksScore += 30;
            }
        }
        // 理论课教学工作量
        if (worksApply.getTheoryWorks() != null && !worksApply.getTheoryWorks().isEmpty()){
            for (TheoryWork theoryWork : worksApply.getTheoryWorks()) {
                if (ClassCategory.THEORY.equals(theoryWork.getClassCategory())) {
                    worksScore += theoryWork.getPeriod() * gradeCoefficient.getTheoryCourse();
                }
            }
        }

        // 实践课
        if (worksApply.getPracticeWorks() != null && !worksApply.getPracticeWorks().isEmpty()) {
            for (PracticeWork practiceWork : worksApply.getPracticeWorks()) {
                if (practiceWork.getClassCategory() != null) {
                    if (ClassCategory.PRACTICE.equals(practiceWork.getClassCategory())) {
                        worksScore += practiceWork.getPeriod() * gradeCoefficient.getPracticeCourse();
                    }
                    if (ClassCategory.DISSECTION.equals(practiceWork.getClassCategory())) {
                        worksScore += practiceWork.getPeriod() * gradeCoefficient.getDissectionCourse();
                    }
                    if (ClassCategory.SPORT.equals(practiceWork.getClassCategory())) {
                        worksScore += practiceWork.getPeriod() * gradeCoefficient.getSportCourse();
                    }
                }
            }
        }

        // 选修课教学工作量
        if (worksApply.getOptionalWorks() != null && !worksApply.getOptionalWorks().isEmpty()){
            for (OptionalWork optionalWork : worksApply.getOptionalWorks()) {
                if (ClassCategory.OPTIONAL.equals(optionalWork.getClassCategory())) {
                    worksScore += optionalWork.getPeriod() * gradeCoefficient.getOptionalCourse();
                }
            }
        }

        return worksScore;
    }
}
